package com.csc775.networking;

import java.net.*;
import java.io.*;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
//import com.csc775.gui.AndroidClient;
import com.csc775.AndroidWalkieTalkieActivity;
import com.csc775.gui.TalkActivity;
import com.csc775.message.ControlMessage;
import com.csc775.message.ControlRquestType;

public class Client {
	private Socket TCPsocket = null;                         //Socket for TCP
	private DataInputStream console = null;                  //Datainput stream for receiving message 
	private DataOutputStream streamOut = null;               //Dataoutput stream for sending message 
	private DataInputStream in = null;                       //Datainput stream for receiving message 
	private DataOutputStream out = null;                     //Dataoutput stream for sending message
	private ObjectInputStream Sin = null;                    //Object input stream for receiving message
	private ObjectOutputStream Sout = null;                  //object output stream for sending message 
	private DatagramSocket UDPsocket;                        //Socket for UDP
	private int group = 0;                                   //group number
	String hostname;                                         //hostname string
	boolean connected = true;                                //checks if connected
	ObjectOutputStream oos;                                  //object output stream for TCP 
	ObjectInputStream ois;                                   //object input stream for TCP 
	ControlMessage msg;                                      //control message to send to server

	/**
	 * invoked after the client thread starts
	 * @return
	 */
	public boolean run() {
		try {
			Log.d("EditText", "C: Connecting...");
			Socket TCPsocket = new Socket(AndroidWalkieTalkieActivity.serverIP,
					AndroidWalkieTalkieActivity.serverPort);
			oos = new ObjectOutputStream(TCPsocket.getOutputStream());
			ois = new ObjectInputStream(TCPsocket.getInputStream());
			Log.d("EditText", "C: Closed.");
			} catch (ConnectException ex) {
			return false;
		} catch (Exception e) {
			Log.e("EditText", "C: Error", e);
			connected = false;
		}
		return true;
	}
	/**
	 * to get the TCP output stream
	 * @return
	 */
	public ObjectOutputStream getOos() {
		return oos;
	}

	/**
	 * to get the TCP input stream
	 * @return
	 */
	public ObjectInputStream getOis() {
		return ois;
	}

	/**
	 * client receives message
	 * @return
	 */
	public ControlMessage recevMsg() {
		try {
			String message = (String) ois.readObject().toString();
			System.out.println("from server>" + message);
			msg = ControlMessage.getControlMessageInstance(message);

		} catch (Exception e) {
			System.out.println(e);
		}
		return msg;
	}

	/**
	 * client sends message
	 * @param msg
	 */
	public void Sendmessage(String msg) {

		try {
			oos.writeObject(msg);
			oos.flush();

		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	/**
	 * User selects group
	 * 
	 * @return
	 */
	public int selectGroup() {

		return group++;
	}

	/**
	 * stops the current thread
	 * closes the socket
	 */
	public void stop() {
		try {
			if (console != null)
				console.close();
			if (streamOut != null)
				streamOut.close();
			if (TCPsocket != null)
				TCPsocket.close();
			if (UDPsocket != null)
				UDPsocket.close();
			if (Sout != null)
				Sout.close();
			if (Sin != null)
				Sin.close();
		} catch (IOException ioe) {
			System.out.println("Error closing ...");
		}
	}

	/**
	 * creates a datagram packet
	 * @param message
	 * @param host
	 * @param port
	 * @return
	 * @throws IOException
	 */
	public DatagramPacket buildPacket(String message, String host, int port)
			throws IOException {

		// Create a byte array from a string
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		DataOutputStream dataOut = new DataOutputStream(byteOut);
		dataOut.writeBytes(message);
		byte[] data = byteOut.toByteArray();
		// Return the new object with the byte array payload
		return new DatagramPacket(data, data.length,
				InetAddress.getByName(host), port);
	}

}
